<?php

include_once "../lib/string.class.php";

// TODO: localizzazione

class uploader {
	
	var $basedir;
	var $preventDuplicates;
	var $createDirectory;
	
	function uploader($basedir = false, $preventDuplicates = true, $createDirectory = true) {
		if (!$basedir) {
			$this->basedir = getcwd().DIRECTORY_SEPARATOR;
		} else {
			$this->basedir = $basedir.DIRECTORY_SEPARATOR;
		}
		$this->preventDuplicates = $preventDuplicates;
		$this->createDirectory = $createDirectory;
	}
	
	function upload($fieldName, $directory = '', $allowed_extensions = false, $maxFilesize = 2097152 ) {
		
		if (($maxFilesize && is_numeric($maxFilesize) && $_FILES[$fieldName]["size"] > $maxFilesize) || $_FILES[$fieldName]['error'] == 1) {
			$GLOBALS['Template']->response("Impossibile effettuare l'upload, il file ha dimensioni maggiori di quelle consentite (". string_class::human_filesize($maxFilesize) .")", TEMPLATE_ERROR);
			return false;
		} else if ($_FILES[$fieldName]['size'] == 0) {
			$GLOBALS['Template']->response("Impossibile effettuare l'upload, file non valido", TEMPLATE_ERROR);
			return false;
		}
		
		$directory = $this->basedir.$directory;
		
		if (!is_dir($directory)) {
			if ($this->createDirectory) {
				$this->_mkdir_r($directory);
			} else {
				$GLOBALS['Template']->response("Impossibile effettuare l'upload, directory inesistente", TEMPLATE_ERROR);
				return false;
			}
		}
		
		$tmp_fname = string_class::to_unix($_FILES[$fieldName]['name']);
		$parsed_fname = $this->_parse_filename($tmp_fname);
		
		
		if (is_array($allowed_extensions)) {
			for($i = 0; $i < count($allowed_extensions); $i++) {
				$allowed_extensions[$i] = strtolower($allowed_extensions[$i]);
			}
			if(!in_array($parsed_fname['ext'], $allowed_extensions)) {
				$GLOBALS['Template']->response("Impossibile effettuare l'upload, tipo di file non supportato", TEMPLATE_ERROR);
				return false;
			}
		}
		
		if ($this->preventDuplicates) {
			while (file_exists($directory.DIRECTORY_SEPARATOR.$parsed_fname['fname'].$parsed_fname['added_str'].".".$parsed_fname['ext'])) {
				$parsed_fname = $this->_parse_filename($parsed_fname['fname'].'_'.(++$parsed_fname['added']).".".$parsed_fname['ext']);
			}
		}
		$fullPath = $directory.DIRECTORY_SEPARATOR.$parsed_fname['fname'].$parsed_fname['added_str'].".".$parsed_fname['ext'];
		
		if (!move_uploaded_file($_FILES[$fieldName]["tmp_name"], $fullPath)) {
			$GLOBALS['Template']->response("Errore nell'upload dell'immagine", TEMPLATE_ERROR);
			return false;
		}
		
		return $fullPath;
	}
	
	function _parse_filename($fname) {
		$tmp_pieces = explode(".", $fname);
		$out['ext'] = strtolower(array_pop($tmp_pieces));
		$tmp_fname = implode('', $tmp_pieces);
		$tmp_pieces = explode('_', $tmp_fname);
		$tmp_lastp  = end($tmp_pieces);
		if (is_numeric($tmp_lastp)) {
			$out['added'] = array_pop($tmp_pieces);
			$out['added_str'] = "_". $out['added'];
		} else {
			$out['added'] = 0;
			$out['added_str'] = '';
		}
		$out['fname'] = implode("_", $tmp_pieces);
		return $out;
	}

	function _mkdir_r($dirName, $rights=0777){
		$dirs = explode(DIRECTORY_SEPARATOR, $dirName);
		$dir='';
		foreach ($dirs as $part) {
			if ($part != '') {
				$dir .= $part.DIRECTORY_SEPARATOR;
				if (!is_dir($dir)) {
					mkdir($dir, $rights);
				}
			}
		}
    		return $dir;
	}
	
}

?>